package com.yupi.referral.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.referral.common.ErrorCode;
import com.yupi.referral.constant.CommonConstant;
import com.yupi.referral.exception.BusinessException;
import com.yupi.referral.exception.ThrowUtils;
import com.yupi.referral.mapper.ReferralMapper;
import com.yupi.referral.model.dto.referral.ReferralQueryRequest;
import com.yupi.referral.model.entity.Referral;
import com.yupi.referral.model.vo.ReferralVO;
import com.yupi.referral.service.ReferralService;
import com.yupi.referral.service.UserService;
import com.yupi.referral.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author ZRETC
* @description 针对表【referral(内推)】的数据库操作Service实现
* @createDate 2024-06-28 17:11:01
*/
@Service
public class ReferralServiceImpl extends ServiceImpl<ReferralMapper, Referral>
    implements ReferralService{


//    @Resource
//    private UserService userService;

    @Override
    public void validReferral(Referral referral, boolean add) {
        if (referral == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = referral.getTitle();
        String content = referral.getContent();
        String tags = referral.getTags();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param referralQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Referral> getQueryWrapper(ReferralQueryRequest referralQueryRequest) {
        QueryWrapper<Referral> queryWrapper = new QueryWrapper<>();
        if (referralQueryRequest == null) {
            return queryWrapper;
        }
        Long id = referralQueryRequest.getId();
        String title = referralQueryRequest.getTitle();
        String content = referralQueryRequest.getContent();
        List<String> tags = referralQueryRequest.getTags();
        Integer userId = referralQueryRequest.getUserId();
        String sortField = referralQueryRequest.getSortField();
        String sortOrder = referralQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete",false);
//        if(referralQueryRequest.getState() == 1)
//            queryWrapper.eq("status",1);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public ReferralVO getReferralVO(Referral referral, HttpServletRequest request) {
        ReferralVO referralVO = ReferralVO.objToVo(referral);
        // 1. 关联查询用户信息
//        Long userId = referral.getUserId();
//        User user = null;
//        if (userId != null && userId > 0) {
//            user = userService.getById(userId);
//        }
//        UserVO userVO = userService.getUserVO(user);
//        referralVO.setUserVO(userVO);


        return referralVO;
    }

    @Override
    public Page<ReferralVO> getReferralVOPage(Page<Referral> referralPage, HttpServletRequest request) {
        List<Referral> referralList = referralPage.getRecords();
        Page<ReferralVO> referralVOPage = new Page<>(referralPage.getCurrent(), referralPage.getSize(), referralPage.getTotal());
        if (CollUtil.isEmpty(referralList)) {
            return referralVOPage;
        }
//        // 1. 关联查询用户信息
//        Set<Long> userIdSet = referralList.stream().map(Referral::getUserId).collect(Collectors.toSet());
//        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
//                .collect(Collectors.groupingBy(User::getId));

        // 填充信息
        List<ReferralVO> referralVOList = referralList.stream().map(referral -> {
            ReferralVO referralVO = ReferralVO.objToVo(referral);
//            Long userId = referral.getUserId();
//            User user = null;
//            if (userIdUserListMap.containsKey(userId)) {
//                user = userIdUserListMap.get(userId).get(0);
//            }
//            referralVO.setUserVO(userService.getUserVO(user));
            return referralVO;
        }).collect(Collectors.toList());
        referralVOPage.setRecords(referralVOList);
        return referralVOPage;
    }

}




